package com.eveinfo.api.asset;

import java.util.LinkedList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import com.eveinfo.api.AbstractApiHandler;

public class AssetHandler extends AbstractApiHandler<AssetResponse> {

	private LinkedList<String> where;
	private LinkedList<ApiAsset> assetsList;
	private int locationID;
	private LinkedList<ApiAsset> parentAssets;

	public AssetHandler() {
		super();
		this.where = new LinkedList<String>();
		this.response = new AssetResponse();
		this.assetsList = new LinkedList<ApiAsset>();
		this.parentAssets = new LinkedList<ApiAsset>();
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		super.startElement(uri, localName, qName, attributes);
		String value = (!localName.equals("")) ? localName : qName;

		if (value.equals("rowset")) {
			String name = attributes.getValue("name");
			where.addFirst(name);
			if (!name.equals("assets")) {
				final ApiAsset last = assetsList.getLast();
				parentAssets.addFirst(last);
			}
		} else if (value.equals("row")) {
			ApiAsset asset = new ApiAsset();
			asset.setFlag(Integer.parseInt(attributes.getValue("flag")));
			asset.setItemID(Integer.parseInt(attributes.getValue("itemID")));
			asset.setTypeID(Integer.parseInt(attributes.getValue("typeID")));
			asset.setQuantity(Integer.parseInt(attributes.getValue("quantity")));
			asset.setSingleton(Integer.parseInt(attributes.getValue("singleton")));
			String s = attributes.getValue("locationID");
			if (s != null) {
				locationID = Integer.parseInt(s);
			}
			asset.setLocationID(locationID);
			if (!parentAssets.isEmpty()) {
				final ApiAsset parentAsset = parentAssets.getFirst();
				parentAsset.setContainItems(true);
				asset.setParent(parentAsset);
			}
			assetsList.add(asset);
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		super.endElement(uri, localName, qName);
		String value = (!localName.equals("")) ? localName : qName;
		if (value.equals("rowset")) {
			String balise = where.removeFirst();
			if (!parentAssets.isEmpty()) {
				parentAssets.removeFirst();
			}
			if (balise.equals("assets")) {
				response.addAsset(assetsList);
			}
		}
	}
}
